﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using NHibernate;
using Caduceu.Estudos.Erros;

namespace Caduceu.Estudos.DAL
{
    /// <summary>
    /// Objeto usado pela camada de negócio para poder manipular sessões sem ter que possuir
    /// dependência ao NHibernate
    /// </summary>
    public class DbSession : IDisposable
    {
        private const string ERR_NAO_EXISTE_TRANSACAO = "ERR_0003";
        private const string ERR_JA_EXISTE_TRANSACAO = "ERR_0004";

        internal ISession session;
        internal ITransaction transaction = null;
        private bool disposed = false;

        private void CheckTransactionExists()
        {
            if (this.transaction == null)
                throw new InvalidOperationException(Erros.Messages.GetMessage2(ERR_NAO_EXISTE_TRANSACAO));
        }
        
        public DbSession()
        {
            session = NHibernateHelper.GetSession();
        }

        public IDbConnection GetInternalConnection()
        {
            return session.Connection;
        }

        public void BeginTransaction()
        {
            if (this.transaction != null)
                throw new InvalidOperationException(ERR_JA_EXISTE_TRANSACAO);

            transaction = this.session.BeginTransaction();
        }

        public void CommitTransaction()
        {
            CheckTransactionExists();
            transaction.Commit();
        }

        public void RollbackTransaction()
        {
            CheckTransactionExists();
            transaction.Rollback();
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (!this.disposed)
            {
                session.Dispose();
                this.disposed = true;
            }
        }

        #endregion
    }
}
